<template>
    <div>
        <div class="crumbs">
            <div class="contentbox">
                <div class="contentsize">新订合同</div>
                <div>
                    <el-button type="primary" @click="submitForm('ruleForm')" :disabled="getsubmit">保存</el-button>
                    <el-button @click="cacelsubmitForm('ruleForm')">返回</el-button>
                </div>
            </div>
        </div>
        <div class="container">
            <div class="addtitle">房屋信息</div>
            <div class="detailcontent">
                <!-- scope.row.beginTime == null ? '' : scope.row.beginTime.trim().split(' ')[0] -->
                <div class="detailitem1">{{ projectdetail.fwdz }}</div>
                <div class="detailitem">管房单位：{{ projectdetail.gfdw }}</div>
                <div class="detailitem">档案编号：{{ projectdetail.dabh }}</div>
                <div class="detailitem">房屋性质：{{ projectdetail.fwyt }}</div>
                <div class="detailitem">房屋结构：{{ projectdetail.fwjg }}</div>
                <div class="detailitem">产权单位：{{ projectdetail.cqdw }}</div>
                <div class="detailitem">建筑面积：{{ projectdetail.jzmj }}</div>
                <div class="detailitem">建筑年代：{{ projectdetail.jznd }}</div>
                <div class="detailitem">建筑形式：{{ projectdetail.jzxs }}</div>
                <div class="detailitem"></div>
            </div>
            <div class="addtitle">租户信息</div>
            <el-form ref="form" :model="form" label-width="120px" :inline="true" label-position="top">
                <el-form-item label="承租人:" style="width: 30%" prop="czr ">
                    <el-input v-model="form.czr" placeholder="请输入承租人" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="承租人联系方式:" style="width: 30%" prop="czrlxfs">
                    <el-input v-model="form.czrlxfs" placeholder="请输入承租人联系方式" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="证件名称:" style="width: 30%" prop="zjmc">
                    <el-input v-model="form.zjmc" placeholder="请输入证件名称" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="证件号码:" style="width: 30%" prop="zjhm">
                    <el-input v-model="form.zjhm" placeholder="请输入证件号码" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="联系地址:" style="width: 30%" prop="lxdz ">
                    <el-input v-model="form.lxdz" placeholder="请输入联系地址" class="search-input"></el-input>
                </el-form-item>
                <!-- <el-form-item label="其他联系电话:" style="width: 30%" prop="address">
                    <el-input v-model="form.address" placeholder="请输入其他联系电话" class="search-input"></el-input>
                </el-form-item> -->
                <!-- <div class="buttonCenter">
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <el-button @click="cacelsubmitForm('ruleForm')">取消</el-button>
                </div> -->
            </el-form>
            <div class="addtitle">合同信息</div>
            <!-- :picker-options="pickerOptionstart" -->
            <el-form ref="form" :model="form" label-width="120px" :inline="true" label-position="top">
                <el-form-item label="合同签订日期:" style="width: 30%" prop="qdsj">
                    <el-date-picker type="date" placeholder="选择合同签订时间" v-model="form.qdsj" style="width: 100%"
                        value-format="yyyy-MM-dd" ></el-date-picker>
                </el-form-item>
                <el-form-item label="合同到期日期:" style="width: 30%" prop="dqsj">
                    <el-date-picker type="date" placeholder="选择合同到期日期" v-model="form.dqsj" style="width: 100%"
                        value-format="yyyy-MM-dd" @focus="pickDateEnd" :picker-options="pickerOptionend"></el-date-picker>
                </el-form-item>
                <el-form-item label="每月金额:" style="width: 30%" prop="yzj">
                    <el-input v-model="form.yzj" placeholder="请输入每月金额" class="search-input">
                        <template slot="prepend">￥</template>
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="减免金额:" style="width: 30%" prop="jmje">
                    <el-input v-model="form.jmje" placeholder="请输入减免金额" class="search-input">
                        <template slot="prepend">￥</template>
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="减免原因:" style="width: 30%" prop="jmyy">
                    <el-input v-model="form.jmyy" placeholder="请输入减免原因" class="search-input"></el-input>
                </el-form-item>
                <!-- <el-form-item label="押金:" style="width: 30%" prop="yj">
                    <el-input v-model="form.yj" placeholder="请输入押金" class="search-input">
                        <template slot="prepend">￥</template>
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item> -->
                <el-form-item style="width: 100%" prop="sbqd" label="设备清单:">
                    <el-checkbox-group v-model="sbqd">
                        <el-checkbox label="暖气"></el-checkbox>
                        <el-checkbox label="宽带"></el-checkbox>
                        <el-checkbox label="冰箱"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <!-- fj -->
                <el-upload class="upload-demo" :action="httpUrl + '/file/uploadFile'"
                    :on-remove="(file, fileList) => { handleRemoves(file, fileList, 'fj') }" :before-remove="beforeRemoves"
                    multiple :on-success="(response, file, fileList) => handelfilesuccess(response, file, fileList, 'fj')"
                    :headers="myHeaders" :file-list="filefileList">
                    <div class="unloadTitle">附件</div>
                    <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
                </el-upload>
                <el-button size="small" type="primary" @click="gettime(form.qdsj, form.dqsj, form.yzj, form.jmje)"
                    style="margin: 0 auto 10px;">按年月分配金额</el-button>
                <span style="color: red;margin-left: 10px;font-size: 12px;">点击按年月分配金额后才可以保存</span>
                <el-table :data="tableData" border :header-cell-style="{
                    background: '#f8fbff',
                    color: '#173686',
                    border: '0',
                }" style="width: 100%" size="mini" show-summary sum-text="合计" :summary-method="getSummaries"
                    :row-style="{ height: '20px' }" :cell-style="{ padding: '0px' }">
                    <el-table-column prop="year" label="年份" align="center"> </el-table-column>
                    <el-table-column prop="month" label="月份" align="center"> </el-table-column>
                    <!-- <el-table-column prop="jfrq" label="缴费日期" align="center"> </el-table-column> -->
                    <el-table-column label="月应缴金额" align="center" prop="yyjje"></el-table-column>
                    <el-table-column label="减免金额" align="center" prop="jmje"></el-table-column>
                    <el-table-column label="应缴金额" align="center" prop="yjje"></el-table-column>
                    <el-table-column label="交款金额" align="center" prop="jkje"></el-table-column>
                    <!-- <el-table-column label="实际金额(元)" align="center" prop="ssje"></el-table-column> -->
                </el-table>
            </el-form>
            <div class="addtitle" style="margin-top: 20px;">办理入住(入住信息)</div>
            <el-form ref="form" :model="form" label-width="120px" :inline="true" label-position="top">
                <el-form-item label="水表:" style="width: 30%" prop="shb">
                    <el-input v-model="form.shb" placeholder="请输入水表" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="电表:" style="width: 30%" prop="db">
                    <el-input v-model="form.db" placeholder="请输入电表" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="燃气表:" style="width: 30%" prop="rqb">
                    <el-input v-model="form.rqb" placeholder="请输入燃气表" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="年度供热费:" style="width: 30%" prop="ndgrf">
                    <el-input v-model="form.ndgrf" placeholder="请输入年度供热费" class="search-input"></el-input>
                </el-form-item>
                <el-form-item label="物业费:" style="width: 30%" prop="wyf">
                    <el-input v-model="form.wyf" placeholder="请输入物业费" class="search-input"></el-input>
                </el-form-item>
                <el-form-item style="width: 30%" prop="wyf"></el-form-item>
                <el-form-item label="设施设备情况:" style="width: 100%" prop="sbqk">
                    <el-input v-model="form.sbqk" placeholder="请输入设施设备情况" class="search-input" type="textarea" :autosize="{ minRows: 4 }"></el-input>
                </el-form-item>
                <!-- rzfj  -->
                <el-upload class="upload-demo" :action="httpUrl + '/file/uploadFile'"
                    :on-remove="(file, fileList) => { handleRemoves(file, fileList, 'rzfj') }"
                    :before-remove="beforeRemoves" multiple
                    :on-success="(response, file, fileList) => handelfilesuccess(response, file, fileList, 'rzfj')"
                    :headers="myHeaders" :file-list="filefileList">
                    <div class="unloadTitle">附件</div>
                    <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
                </el-upload>
            </el-form>
        </div>
    </div>
</template>
<script>
import { builddetail, signlistadd } from '@/api/index';
import global from '@/components/common/httpurl.vue'
export default {
    name: 'addht',
    data() {
        return {
            getsubmit: true,
            httpUrl: global.httpUrl,//公共地址
            filefileList: [],//文件列表
            fileListshandle: [],
            // 请求表头信息
            myHeaders: {
                'token': localStorage.getItem('token')
            },
            fileList: [],
            tableData: [],//可编辑表格
            projectdetail: {},//楼幢详情
            sbqd: [],//设备清单
            form: {
                create_name: "",
                create_name_id: "",
                create_time: "",
                current: 0,
                czr: "",//承租人
                czrlxfs: "",//承租人联系方式
                db: "",//电表
                dqsj: "",// 合同到期时间
                fj: "",//附件 
                htbh: "",//合同编号 
                // id: "",
                jmje: 0,//减免金额
                jmyy: "",//减免原因
                lxdz: "",//联系地址
                ndgrf: "",//年度供热费
                nzj: "",//年租金
                pageSize: 0,
                qdsj: "",//合同签订时间
                relid: "",
                rqb: "",//燃气表 
                rzfj: "",//入住附件
                sbqd: "",//设备清单 
                shb: "",//水表
                status_code: 1,//1正常 2删除 
                type: this.$store.getters.type,//分类 1:房间 2：楼栋 
                update_name: "",
                update_name_id: "",
                update_time: "",
                wyf: "",//物业费 
                yj: "",//押金
                yzj: "",//月租金
                ysje: 0,//
                zjList: [
                    {
                        create_name: "",
                        create_name_id: "",
                        create_time: "",
                        current: 0,
                        id: "",
                        jfrq: "",//缴费日期 
                        jkje: "",//交款金额
                        jmje: "",//减免金额 
                        month: "",//月 
                        pageSize: 0,
                        signid: "",
                        sjzt: "",//数据状态
                        status_code: 1,//1正常 2删除
                        update_name: "",
                        update_name_id: "",
                        update_time: "",
                        year: "",//年份 
                        yjje: "",//应缴金额
                        yyjje: ""//月应缴金额
                    }
                ],
                zjhm: "",//证件号码
                zjmc: "",//证件名称
                zjsjzq: ""//租金收缴周期
            },
            // 开始时间限制到今年之后
            pickerOptionstart: {
                disabledDate(time) {
                    var year = new Date().getFullYear() - 1
                    console.log(year)
                    console.log(time.getTime())
                    return (
                        time.getTime() < new Date(year + '-12-31').getTime()
                    )
                }
            },
            // 结束时间比开始时间大
            pickerOptionend: {},
        };
    },
    methods: {
        // 时间转换
        stringDateToTimestamp(stringDate) {
            return Date.parse(new Date(stringDate));
        },
        // 获取终止日期
        pickDateEnd() {
            let idStartDate = this.form.qdsj;
            if (!idStartDate) return;
            let that = this;
            that.pickerOptionend = {
                disabledDate(time) {
                    return time.getTime() <= that.stringDateToTimestamp(idStartDate);
                },
            };
        },
        // 创建
        submitForm() {
            this.form.sbqd = this.sbqd.toString()
            this.form.zjList = this.tableData
            console.log(this.form)
            signlistadd(this.form).then((res) => {
                if (res.code == 200) {
                    this.$message.success('创建成功');
                    this.$router.go(-1);
                } else {
                    this.$message.error('创建失败');
                }
            });

            console.log('提交确定');
        },
        // 取消
        cacelsubmitForm() {
            this.$router.go(-1);
        },
        // 文件
        handleRemoves(file, fileList, filetype) {
            console.log(fileList)
            console.log('filetype', filetype)
            this.fileListshandle = fileList.map((res) => {
                return res.response.data.id;
            });
            this.form[filetype] = this.fileListshandle.toString()

        },
        // 文件删除前
        beforeRemoves(file, fileList) {
            console.log(file)
            console.log(fileList)
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 上传成功
        handelfilesuccess(response, file, fileLists, filetype) {
            console.log(fileLists)
            console.log('filetype', filetype)
            this.$message.success('导入成功');
            this.fileListshandle = fileLists.map((res) => {
                console.log(res.response.data)
                return res.response.data.id;
            });
            this.form[filetype] = this.fileListshandle.toString()
        },
        // 月份划分(列表数据计算)
        gettime(start, end, myzj, sjjmje) {
            if (start && end) {
                if (myzj) {
                    let ranges = []
                    let [i, j] = [start, end].map(i => new Date(i)).sort((a, b) => a - b)
                    console.log([i, j])
                    while (i <= j) {
                        const ysyf = jfrq//应收月份
                        const jkfs = ''//付款方式
                        const skrq = zzrq//收款日期
                        const id = ''
                        const signid = ''
                        const status_code = '1'
                        const ssje = myzj//实际金额
                        const jmje = sjjmje//减免金额
                        const jfrq = i.toISOString().slice(0, 10)//开始日期
                        const year = jfrq.split('-')[0]//应收年份
                        const month = jfrq.split('-')[1]//应收年月
                        i = new Date(i.getFullYear(), i.getMonth() + 1, 0, i.getHours())
                        const zzrq = new Date(Math.min(+i, +j)).toISOString().slice(0, 10)//终止日期
                        const yyjje = myzj//月应收金额
                        const yjje = myzj - sjjmje//应收金额
                        const jkje = '0'
                        i.setDate(i.getDate() + 1)
                        ranges.push({ year, month, jfrq, yyjje, jmje, yjje, jkje, zzrq, ssje, status_code })
                        // 第一条
                        const firstval = ranges[0]
                        console.log(firstval.zzrq.split('-')[2] - firstval.jfrq.split('-')[2])
                        firstval.ssje = ((firstval.yyjje / (firstval.zzrq.split('-')[2])) * (firstval.zzrq.split('-')[2] - firstval.jfrq.split('-')[2] + 1)).toFixed(2)//数组第一条实际金额
                        console.log(firstval.ssje)
                        firstval.yjje = firstval.ssje - sjjmje//数组第一条应缴金额
                        // 最后一条
                        const lastval = ranges[ranges.length - 1]
                        console.log(lastval.zzrq.split('-')[0])
                        console.log((lastval.zzrq.split('-')[1]) + 1)
                        var d = new Date(lastval.zzrq.split('-')[0], (lastval.zzrq.split('-')[1]), 0);
                        console.log('d', d.getDate(), lastval.yyjje / d)
                        lastval.ssje = ((lastval.yyjje / d.getDate()) * ((lastval.zzrq.split('-')[2]) - (lastval.jfrq.split('-')[2]) + 1)).toFixed(2)//数组最后一条实际金额
                        console.log(lastval.ssje)
                        lastval.yjje = lastval.ssje - sjjmje//数组最后一条应缴金额
                    }
                    this.tableData = ranges
                    this.tableData.map(item => {
                        delete item.ssje
                        delete item.zzrq
                    })
                    this.form.zjsjzq = this.tableData.length
                    this.getsubmit = false//保存可以点击
                    console.log(ranges)
                } else {
                    this.$message.error('请填写每月金额！！')
                }
            } else {
                this.$message.error('请选择开始结束日期！！')
            }

        },
        // 合并计算某一列
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                // 只对amount这一列进行总计核算。
                if (column.property === 'yyjje') {
                    sums[index] = '---'
                    // if (!values.every(value => isNaN(value))) {
                    //     sums[index] = values.reduce((prev, curr) => {
                    //         const value = Number(curr);
                    //         if (!isNaN(value)) {
                    //             return prev + curr;
                    //         } else {
                    //             return prev;
                    //         }
                    //     }, 0);
                    //     sums[index] += ' 元';
                    // } else {
                    //     sums[index] = '---'
                    // }
                } else if (column.property === 'yjje') {
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += '';
                    } else {
                        sums[index] = '---'
                    }
                    sums[index] = Number(sums[index]).toFixed(2)
                } else {
                    sums[index] = '---'
                }
            });
            console.log('tableData', this.tableData)
            console.log('sums', sums)
            this.form.nzj = sums[4]
            return sums;
        },
        // 楼幢详情
        builddetail(data) {
            builddetail(data).then((res) => {
                this.projectdetail = res.data;
            });
        },
    },
    created() {
        this.form.relid = this.$route.params.id
        console.log(this.$route.params)
        let data = {
            id: this.$route.params.id
        };
        this.builddetail(data);
        console.log(global.httpUrl)
    }
};
</script>
<style>
.el-upload-list {
    width: 60%;
}

.el-upload--text {
    width: auto;
    height: 80px;
    overflow: hidden;
    border: none;
}
</style>
<style scoped>
.container {
    overflow: hidden;
}

.crumbs {
    background-color: #fff;
    padding: 20px 20px;
}

.indexTitle {
    margin-bottom: 20px;
}

.contentbox {
    display: flex;
    justify-content: space-between;
}

.contentsize {
    font-size: 18px;
    font-weight: 700;
    line-height: 32px;
    color: #606266;
}

.handle-box {
    overflow: hidden;
}

.addtitle {
    width: 100%;
    border-bottom: 1px solid #eeeeee;
    padding-bottom: 20px;
    box-sizing: border-box;
    margin-bottom: 20px;
    font-weight: 700;
}

.buttonCenter {
    width: 12%;
    margin: auto;
}

.unloadTitle {
    text-align: left;
    padding-bottom: 10px;
    box-sizing: border-box;
    color: #606266;
}

/* 搜索按钮 */
.searchcolor {
    background-color: #7090ff;
}

.detailcontent {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

.detailcontent .detailitem {
    /* float: left; */
    width: 33%;
    margin-bottom: 30px;
}

.detailcontent .detailitem1 {
    /* float: left; */
    width: 99%;
    margin-bottom: 30px;
    font-weight: 700;
    color: #008A94;
}
</style>